<?php
class ForumTheme extends CActiveRecord {
    
    public $themeId;
    public $title;
    public $isSupport;
    public $partnerId;
    public $date;
    public $userId;
    public $url;
    
    public $type;
    public $subscr;
    public $subscrEmail;
    public $text;
    public $deletedImg;
    public $firstComId;


    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return 'forum_theme';
    }
    
    public function attributeLabels() {
        return array(
            'title' => 'Тема',
            'text' => 'Сообщение', 
        );
    }
    
    public function beforeValidate() {
        if(!parent::beforeValidate()) return false;
        $this->attributes = !empty($_POST[get_class($this)]) ? $_POST[get_class($this)] : array();
        return true;
    }
    
    protected function beforeDelete() {
        // ajax/delFofumTh
        $id = $this->getPrimaryKey();
        $com = Yii::app()->db->createCommand()->select('comId')->from('forum_comments')->where('`themeId`='.$id)->queryAll();
        $comId = array();
        foreach($com as $c) $comId[] = $c['comId'];
        $images = Yii::app()->db->createCommand()->select('bigImg, smallImg')->from('forum_images')->where(array('in', 'comId', $comId))->queryAll();
        for($i=0; $i<count($images); $i++) {
            if(file_exists(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['bigImg'])) 
                unlink(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['bigImg']);
            if(file_exists(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['smallImg'])) 
                unlink(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['smallImg']);
        }
        Yii::app()->db->createCommand()->delete('forum_images', '`comId` in('.implode(',',$comId).') ');
        Yii::app()->db->createCommand()->delete('forum_theme', '`themeId`='.$id);
        Yii::app()->db->createCommand()->delete('forum_comments', '`themeId`='.$id);
        Yii::app()->db->createCommand('UPDATE `partners` SET `countComments`=countComments - '.count($com).' WHERE `partnerid`="'.$forumTh['partnerId'].'"')->query();
        return parent::beforeDelete();
    }
    
    public function rules() {
        return array(
            array('isSupport, subscr, partnerId, type, deletedImg, firstComId', 'safe'),
            array('subscrEmail', 'email', 'message'=>'Введенный вами email содержит ошибки'),
            array('title, text', 'required', 'message' => '{attribute} не может быть пустым'),
        );
    }
    
    public function beforeSave() {
        if(!parent::beforeSave()) return false;
        if($this->getIsNewRecord()) {
            $this->date = time();
            $this->userId = Yii::app()->user->isGuest ? 0 : Yii::app()->user->getId();
        } else {
            if(!empty($this->deletedImg)) {
                $images = explode(',', $this->deletedImg);
                Yii::app()->db->createCommand()->delete('forum_images', '`smallImg` in("'.str_replace(',', '","', $this->deletedImg).'")');
                for($i=0; $i<count($images); $i++) {
                    if(file_exists($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$images[$i]))
                        unlink($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$images[$i]);
                    if(file_exists($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.str_replace('sm', '', $images[$i])))
                        unlink($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.str_replace('sm', '', $images[$i]));
                }
            }
        }
        $url = CPartnerkiHelper::toTranslit(mb_strtolower($this->title, 'UTF-8'));
        $urls = Yii::app()->db->createCommand()->select('url')->from('forum_theme')->where('url like "%'.$url.'_%" or url="'.$url.'"')->order('url asc')->queryAll();
        if(empty($urls)) {
            $this->url = $url;
        } else {
            $res = array();
            foreach ($urls as $u) $res[] = $u['url']; 
            if(!in_array($url, $res)) {
                $this->url = $url;
            } else {
                $i=1;
                while (1) {
                    if(!in_array($url.'_'.$i, $res)) {
                        $this->url = $url.'_'.$i;
                        break;
                    }
                    $i++;
                }
            }
        }
        return true;
    }
    
    public function relations() {
        return array(
            'comments'=>array(self::HAS_MANY, 'ForumComments', 'themeId', 'limit'=>'1'),
            'countComment'=>array(self::STAT, 'ForumComments', 'themeId'),
            'images' => array(self::HAS_MANY, 'ForumImages', array('typeId'=>'themeId'), 'on'=>'`images`.`type`="forum"')
        );
    }
    
    public function afterSave() {
        if($this->getIsNewRecord()){
            if(!empty($this->subscrEmail) || $this->subscr) {
                if(Yii::app()->user->isGuest) {
                    Yii::app()->db->createCommand()->insert('subscribers', array('type'=>'forum_topic', 'typeId'=>$this->primaryKey, 'email'=>$this->subscrEmail, 'userId'=>'0', 'date'=>time() ));
                } else {
                    Yii::app()->db->createCommand()->insert('subscribers', array('type'=>'forum_topic', 'typeId'=>$this->primaryKey, 'email'=>Yii::app()->user->getState('email'), 'date'=>time(), 'userId'=>Yii::app()->user->getId() ));
                }
            }
            Yii::app()->db->createCommand()->insert('mailer_auto', array('type'=>'forum', 'typeId'=>$this->partnerId, 'childId'=>$this->primaryKey, 'date'=>time()));
            Yii::app()->db->createCommand('UPDATE `partners` SET `countComments`=countComments + 1 WHERE `partnerid`='.$this->partnerId)->query();
            Yii::app()->db->createCommand()->insert('forum_comments', array('themeId'=>$this->primaryKey, 'text'=>$this->text, 'userId'=>$this->userId, 'comDate'=>time(), 'isFirst'=>'1', 'userIp'=>CHttpRequest::getUserHostAddress()));
            
            #отправляю сообщение правдставителям партнерки, что им задали вопрос.
            if($this->isSupport) $this->sendDelegateMess();
        } else {
            Yii::app()->db->createCommand()->update('forum_comments', array('text'=>$this->text), '`isFirst`=1 and themeId='.$this->primaryKey);
        }
        $userFiles = Yii::app()->user->getState('xuploadFiles', array());
        if(!empty($userFiles)) {
            $comId = $this->getIsNewRecord() ? Yii::app()->db->lastInsertID : $this->firstComId;
            foreach ($userFiles as $k=>$v) {
                $this->changeImage($k);
                Yii::app()->db->createCommand()->update('forum_images', array('comId'=>$comId, 'smallImg'=>'sm'.$k), 'bigImg = :bigName', array(':bigName'=>$k));
            }
        }
    }
    
    private function sendDelegateMess() {
        $partner = Yii::app()->db->createCommand()->select('p.name, p.url, p.delegate1, p.delegate2, c.catId, c.name as catName, c.parentId')->from('partners p')->join('partners_cat c', '`c`.`catId`=`p`.`catId`')->where('`partnerid`='.$this->partnerId)->queryRow();
        $delegates = Yii::app()->db->createCommand()->select('login, userid')->from('users')->where('userid in('.$partner['delegate1'].','.$partner['delegate2'].')')->queryAll();
        for($i=0; $i<count($delegates); $i++) {
            $dialogs = Yii::app()->db->createCommand()->select('d.*')->from('messages_dialogs d')->where('(d.user1Id IN('.$partner['delegate1'].','.$partner['delegate2'].') AND d.user2Id=0) OR (d.user2Id IN('.$partner['delegate1'].','.$partner['delegate2'].') and d.user1Id=0)')->queryAll();
            $dialog = false;
            if(!empty($dialogs)) {
                for($l=0; $l<count($dialogs); $l++) {
                    if($dialogs[$l]['user1Id'] == $delegates[$i]['userid'] || $dialogs[$l]['user2Id'] == $delegates[$i]['userid']) {
                        $dialog = $dialogs[$l]; break;
                    }
                }
            }
            if($dialog) {
                $targetField = $dialog['user1Id'] == 0 ? 'user2New' : 'user1New';
                $target = $dialog['user1Id'] == 0 ? $dialog['user2Id'] : $dialog['user1Id'];
                $newMessTarget = $dialog['user1Id'] == 0 ? 'user2Del' : 'user1Del';;
                Yii::app()->db->createCommand()->insert('messages', array('dialogId'=>$dialog['dialogId'], 'toId'=>$target, 'fromId'=>'0', 'sendDate'=>time(), 'message'=>Yii::app()->controller->renderPartial('//messages/newDelegateQuestion', array('user'=>$delegates[$i], 'partner'=>$partner, 'themeId'=>$this->themeId), true)));
                Yii::app()->db->createCommand()->update('messages_dialogs', array($targetField=>$target, 'lastMessId'=>Yii::app()->db->lastInsertID, $newMessTarget=>'0'), '`dialogId`='.$dialog['dialogId']);
            } else {
                Yii::app()->db->createCommand()->insert('messages_dialogs', array('user1Id'=>$delegates[$i]['userid'], 'user2Id'=>'0', 'user1New'=>$delegates[$i]['userid'] ));
                $dialogId = Yii::app()->db->lastInsertID;
                Yii::app()->db->createCommand()->insert('messages', array('dialogId'=>Yii::app()->db->lastInsertID, 'toId'=>$delegates[$i]['userid'], 'fromId'=>'0', 'sendDate'=>time(), 'message'=>Yii::app()->controller->renderPartial('//messages/newDelegateQuestion', array('user'=>$delegates[$i], 'partner'=>$partner, 'themeId'=>$this->themeId), true)));
                Yii::app()->db->createCommand()->update('messages_dialogs', array('lastMessId'=>Yii::app()->db->lastInsertID), '`dialogId`='.$dialogId);
            }
        }
    }
    
    private function changeImage($img) {
        if(!file_exists($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$img)) return 0;
        Yii::app()->ih->load($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$img)->watermark($_SERVER['DOCUMENT_ROOT'] . '/images/prettyImg/watermark.png', 10, 20, CImageHandler::CORNER_CENTER, 0.3)->save($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$img);
        Yii::app()->ih->load($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$img)->resize(80, 80)->save($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/sm'.$img);
    }
    
    public function pagination($limit, $offset) {
        $this->getDbCriteria()->mergeWith(array(
            'offset' => $offset, 'limit' => $limit,
        ));
        return $this;
    }
}

/*if($this->getScenario() == 'update') {
            Yii::app()->db->createCommand()->delete('reviews_ratings', 'revId=:id', array(':id'=>$this->primaryKey));
            if(!empty($this->deletedImg)) {
                $this->deletedImg = explode(',', $this->deletedImg);
                for($i=0; $i<count($this->deletedImg); $i++) {
                    Images::model()->deleteAll('`smallImg`="'.$this->deletedImg[$i].'"');
                    if(file_exists($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.$this->deletedImg[$i]))
                        unlink($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.$this->deletedImg[$i]);
                    if(file_exists($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.str_replace('sm', '', $this->deletedImg[$i])))
                        unlink($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.str_replace('sm', '', $this->deletedImg[$i]));
                }
            }
        }*/